import { createContext, useContext, useReducer } from 'react';

const FAKE_USER = {
  name: 'Jack',
  email: 'jack@example.com',
  password: 'qwerty',
  avatar: 'https://img.loliapi.cn/i/pp/img100.webp'
};

const initialState = {
  user: null,
  isAuthenticated: false
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'login':
      return { ...state, user: action.payload, isAuthenticated: true };
    case 'logout':
      return { ...state, user: null, isAuthenticated: false };
    default:
      throw new Error(`Unhandled action type: ${action.type}`);
  }
};

const FakeAuthContext = createContext();

const FakeAuthProvider = ({ children }) => {
  const [{ isAuthenticated, user }, dispatch] = useReducer(
    reducer,
    initialState
  );

  function login(email, password) {
    if (email === FAKE_USER.email && password === FAKE_USER.password) {
      dispatch({ type: 'login', payload: FAKE_USER });
    } else {
      throw new Error('Invalid email or password');
    }
  }

  function logout() {
    dispatch({ type: 'logout' });
  }

  return (
    <FakeAuthContext.Provider value={{ isAuthenticated, user, login, logout }}>
      {children}
    </FakeAuthContext.Provider>
  );
};

const useFakeAuth = () => {
  const context = useContext(FakeAuthContext);
  if (context === undefined) {
    throw new Error('useFakeAuth must be used within a FakeAuthProvider');
  }
  return context;
};

export { FakeAuthProvider, useFakeAuth };
